package com.common.android.utils.http;

import java.io.File;
import java.util.ArrayList;
import java.util.Map;

import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.product.android.business.ApplicationVariable;
import com.product.android.commonInterface.allCommonInterfaceImpl.AllCommonCallOtherModel;

import android.graphics.Bitmap;
import android.text.TextUtils;

public class HttpComExt extends HttpCom{
	
	private final static String TAG="HttpComExt";
	private final int AUTHSTATUSCODE =401;
	
	public  HttpComExt(){
		super();
		if(ApplicationVariable.INSTANCE.getCurrentUserInfo()!=null){
			httpclient.setSid(ApplicationVariable.INSTANCE.getCurrentUserInfo().getSessionId()+"");
		}
	}
	/**
     * 增加一个传参构造，区别于无参构造，获取支持https的client时用
     * Creates a new instance of HttpClient.
     * <br>Created 2014-9-25 上午9:55:36
     * @param httpsable
     */
	public  HttpComExt(int httpsable){
		super(httpsable);
		if(ApplicationVariable.INSTANCE.getCurrentUserInfo()!=null){
			httpclient.setSid(ApplicationVariable.INSTANCE.getCurrentUserInfo().getSessionId()+"");
		}
	}
	
	
	public HttpComExt(String sid){
		super();
		httpclient.setSid(sid);
	}
	
	/**
	 * 
	 * Creates a new instance of HttpComExt.
	 *
	 * @param bNewPro
	 */
	public  HttpComExt(boolean bNewPro){
		super(bNewPro);
		if(ApplicationVariable.INSTANCE.getCurrentUserInfo()!=null){
			httpclient.setSid(ApplicationVariable.INSTANCE.getCurrentUserInfo().getSessionId()+"");
		}
	}
	
	
	public void setSid(String sid){
		if(sid==null||"".equals(sid)){
			return;
		}
		httpclient.setSid(sid);
	}
	
	public void  setHttpHeader(){
		if(ApplicationVariable.INSTANCE.getCurrentUserInfo()!=null){
			httpclient.setSid(ApplicationVariable.INSTANCE.getCurrentUserInfo().getSessionId()+"");
		}		
	}
	
	protected String getSidAndReplceUrl(String url,HttpException e) throws HttpException{
		if(e.getStatusCode()==AUTHSTATUSCODE){
		    if(ApplicationVariable.INSTANCE.getIUser() != null){
		        ApplicationVariable.INSTANCE.getIUser().clearSid();
		    }
		   
			String sid = getSid();
			if(!TextUtils.isEmpty(sid)){
				httpclient.setSid(sid);
				//原来的URL里包含SID=，把旧的SID换成新的
				String sidStatement="sid=";
				if(url!=null&&url.contains(sidStatement)){
					int index = url.indexOf(sidStatement);
					int end = url.indexOf("&");
					try {
						if(end!=-1){
							url  = url.substring(0, index+sidStatement.length())+sid+url.substring(end);
						}else{
							url  = url.substring(0, index+sidStatement.length())+sid;
						}
					} catch (Exception e2) {
						throw e;
					}
				}
				//重新生成httpclient对象，以免cookie头使用的是被服务端修改的
				initHttpClient(mIsNewPro);
				setSid(sid);

				return url;
			}
		}
		throw e;
	}
	
	public Response post(String url, JSONObject json) throws  HttpException{		
		try{
			return httpclient.httpRequest(url, json, HttpPost.METHOD_NAME,null,null,null);
		}
		catch(HttpException e){
			url=getSidAndReplceUrl(url, e);
			return httpclient.httpRequest(url, json, HttpPost.METHOD_NAME,null,null,null);
		}
	}
	 
	public Response get(String url) throws  HttpException{
		try{
			return httpclient.httpRequest(url, null, HttpGet.METHOD_NAME,null,null,null);
		}
		catch(HttpException e){
			url=getSidAndReplceUrl(url, e);
			return httpclient.httpRequest(url, null, HttpGet.METHOD_NAME,null,null,null);
		}
	}
	
	 
	/**
	 * 有返回cookie 
	 * @throws HttpAuthException
	 * @throws HttpServerException
	 * @throws HttpException
	 */
	public Response get(String url ,CookieStore cookieStore) throws  HttpException{
		try{
			return httpclient.httpRequest(url, null, HttpGet.METHOD_NAME,null,null,cookieStore);
		}
		catch(HttpException e){
			url=getSidAndReplceUrl(url, e);
			return httpclient.httpRequest(url, null, HttpGet.METHOD_NAME,null,null,cookieStore);
		}
	}
	
	public Response put(String url , JSONObject json ) throws  HttpException{
		try{
			return httpclient.httpRequest(url, json, HttpPut.METHOD_NAME,null,null,null);
		}
		catch(HttpException e){
			url=getSidAndReplceUrl(url, e);
			return httpclient.httpRequest(url, json, HttpPut.METHOD_NAME,null,null,null);
		}
	}

	public Response delete(String url)throws  HttpException{
		try{
			return httpclient.httpRequest(url, null, HttpDelete.METHOD_NAME,null,null,null);
		}
		catch(HttpException e){
			url=getSidAndReplceUrl(url, e);
			return httpclient.httpRequest(url, null, HttpDelete.METHOD_NAME,null,null,null);
		}
	}
	
	public Response post(String url, final File file,final ArrayList<BasicNameValuePair> postParams) throws  HttpException{
		try{
			return httpclient.httpRequest(url,  null, HttpPost.METHOD_NAME,file,postParams,null);
		}
		catch(HttpException e){
			url=getSidAndReplceUrl(url, e);
			return httpclient.httpRequest(url,  null, HttpPost.METHOD_NAME,file,postParams,null);
		}
	}
	
	public Response post(String url, final File file,final ArrayList<BasicNameValuePair> postParams,CookieStore cookiestore) throws  HttpException{
		try{
			return httpclient.httpRequest(url,  null, HttpPost.METHOD_NAME,file,postParams,cookiestore);
		}
		catch(HttpException e){
			url=getSidAndReplceUrl(url, e);
			return httpclient.httpRequest(url,  null, HttpPost.METHOD_NAME,file,postParams,cookiestore);
		}
	}
	
	public Response postByMap(String url, Map<String,String> map) throws  HttpException{
		try{
			return httpclient.httpRequest(url, HttpPost.METHOD_NAME,map);
		}
		catch(HttpException e){
			url=getSidAndReplceUrl(url, e);
			return httpclient.httpRequest(url, HttpPost.METHOD_NAME,map);
		}
	}
	
	public Response updateImg(String url, Bitmap f0) throws  HttpException{		
		try{
			return httpclient.httpUpImageRequest(url, f0, HttpPost.METHOD_NAME);
		}
		catch(HttpException e){
			url=getSidAndReplceUrl(url, e);
			return httpclient.httpUpImageRequest(url, f0, HttpPost.METHOD_NAME);
		}
	}
	
	public Response getAndReloginIfNeed(String url,String oldSid) throws  HttpException{
		try{
			return httpclient.httpRequest(url, null, HttpGet.METHOD_NAME,null,null,null);
		}
		catch(HttpException e){
			if(e.getStatusCode()==AUTHSTATUSCODE){
//				String sid = CommonInterfaceManager.INSTANCE.reloginInterface.onGetReloginSid();
//				ApplicationVariable.INSTANCE.setExpiredSid();
				ApplicationVariable.INSTANCE.getIUser().clearSid();
				String sid = getSid();
				if(!TextUtils.isEmpty(sid)){
					httpclient.setSid(sid);
					url.replace(oldSid, sid);
					return httpclient.httpRequest(url, null, HttpGet.METHOD_NAME,null,null,null);
				}
			}
			throw e;
		}
	}
	
	/**
	 * @n<b>函数名称</b>     :getSid
	 * @brief 重新登录并获取SID
	 * @version    Ver 1.3.3_modularization
	 * @param  @return
	 * @return String
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2014-2-12下午3:24:42      
	*/
	private String getSid(){
		return AllCommonCallOtherModel.MainModel.getRelginSid();
	}
}